package com.zyl.pagergallery_kt.viewModel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.zyl.pagergallery_kt.pojo.PhotoItem
import com.zyl.pagergallery_kt.pojo.Pixabay
import com.zyl.pagergallery_kt.volley.VolleyUtils

class GalleryViewModel(application: Application) : AndroidViewModel(application) {
    //保存请求到的PhotoItem数据
    private val _photoListLive = MutableLiveData<List<PhotoItem>>()

    //将_photoListLive保存成一个只可读的LiveData，给Fragment
    val photoListLive: LiveData<List<PhotoItem>>
        get() = _photoListLive

    //刷新PhotoItem数据的方法
    fun fetchData() {
        //StringRequest 请求Json
        val stringRequest: StringRequest = StringRequest(
                Request.Method.GET,
                getUrl(),
                Response.Listener {
                    //将请求到的String使用Gson解析，然后去除其中的hits，赋值给_photoListLive
                    _photoListLive.value = Gson().fromJson(it, Pixabay::class.java).hits.toList()
                },
                Response.ErrorListener {
                    Log.d("myTAG", "fetchData: JSON请求失败")
                }
        )
        //使用VolleyUtils起请求
        VolleyUtils.getInstance(getApplication()).requestQueue.add(stringRequest)
    }

    //随机产生url
    fun getUrl(): String {
        return "https://pixabay.com/api/?key=20367884-4ff0b66c3d8b80b87f646de62&q=${keyWork.random()}&per_page=100"
    }
    //几个搜索关键词
    val keyWork = arrayListOf("car", "cat", "dog", "big", "pig", "word")

}